package com.share.simple.service.impl;

import com.share.simple.model.CustomUserDetails;
import com.share.simple.model.dto.LoginUserDto;
import com.share.simple.service.LoginService;
import com.share.simple.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录登出
 * @author:caifan
 * @since 2023/7/13
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginUserDto loginUserDto) {

        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUserDto.getUsername(), loginUserDto.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        CustomUserDetails principal = (CustomUserDetails) authenticate.getPrincipal();
//        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        return authentication(principal);
    }

    @Override
    public Boolean logout(String token) throws ParseException {
        Long id = JwtUtil.parseIdByToken(token);
        redisTemplate.delete("login_" + id);
        return true;
    }

    /**
     * 生成token
     * @param customUserDetails
     * @return
     */
    private String authentication(CustomUserDetails customUserDetails) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", customUserDetails.getId());
        map.put("username", customUserDetails.getUsername());
        map.put("password", customUserDetails.getPassword());
        String token = JwtUtil.generateToken(map);
        redisTemplate.opsForValue().set("login_" + customUserDetails.getId(), token);
        redisTemplate.expire("login_" + customUserDetails.getId(), Duration.ofHours(2));
        return token;
    }
}
